package com.vegetable.modules.service.dashboard.impl;

import cn.hutool.core.date.DateUtil;
import com.vegetable.modules.entity.dashboard.*;
import com.vegetable.modules.mapper.dashboard.DashboardMapper;
import com.vegetable.modules.service.dashboard.IDashboardService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 仪表板服务实现类
 *
 * @author qoder
 * @since 2024-01-01
 */
@Slf4j
@Service
@AllArgsConstructor
public class DashboardServiceImpl implements IDashboardService {

    private final DashboardMapper dashboardMapper;

    @Override
    public DashboardOverviewVO getDashboardOverview() {
        return getDashboardOverview(30); // 默认查询30天数据
    }

    @Override
    public DashboardOverviewVO getDashboardOverview(Integer days) {
        log.info("获取仪表板总览数据，时间范围：{}天", days);
        
        DashboardOverviewVO overview = new DashboardOverviewVO();
        
        // 计算时间范围
        LocalDateTime endTime = LocalDateTime.now();
        LocalDateTime startTime = endTime.minusDays(days);
        LocalDateTime today = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
        
        try {
            // 1. 获取财务概览数据
            FinanceOverviewVO financeOverview = new FinanceOverviewVO();
            overview.setFinanceOverview(financeOverview);
            
            // 2. 获取销售趋势数据（最近7天）
            LocalDateTime trendStartTime = endTime.minusDays(7);
            overview.setSalesTrend(dashboardMapper.getSalesTrend(trendStartTime, endTime));
            
            // 3. 获取库存预警数据（前10个）
            overview.setStockAlerts(dashboardMapper.getStockAlerts(10));
            
            // 4. 获取今日业务统计数据
            TodayBusinessVO todayBusiness = new TodayBusinessVO();
            overview.setTodayBusiness(todayBusiness);
            
            // 5. 获取热销商品排行（前10个）
            overview.setHotCommodities(new ArrayList<>());
            
            // 6. 获取客户应收账款数据（前10个）
            overview.setCustomerReceivables(new ArrayList<>());
            
//            // 7. 获取缺货统计数据
//            ShortageStatisticsVO shortageStatistics = dashboardMapper.getShortageStatistics(startTime, endTime);
//            if (shortageStatistics != null) {
//                // 获取缺货明细数据（前10个）
//                List<ShortageDetailVO> shortageDetails = dashboardMapper.getShortageDetails(startTime, endTime, 10);
//                shortageStatistics.setShortageDetails(shortageDetails);
//            }
//            overview.setShortageStatistics(shortageStatistics);
            
            // 8. 获取价格预警数据（前10个）
            // 先获取所有价格预警数据
            List<PriceAlertVO> allPriceAlerts = dashboardMapper.getPriceAlerts(25, new Date()); // 传入默认值25和当前日期
            // 过滤出价格差异超过阈值的数据
            List<PriceAlertVO> filteredPriceAlerts = allPriceAlerts.stream()
                    .filter(alert -> alert.getPriceDifference() != null && 
                                   alert.getAlertThreshold() != null && 
                                   alert.getPriceDifference().compareTo(alert.getAlertThreshold()) >= 0)
                    .collect(Collectors.toList());
            // 取前10个
            List<PriceAlertVO> priceAlerts = filteredPriceAlerts.stream()
                    .limit(10)
                    .collect(Collectors.toList());
            overview.setPriceAlerts(priceAlerts);
            
        } catch (Exception e) {
            log.error("获取仪表板总览数据异常", e);
            throw new RuntimeException("获取仪表板数据失败：" + e.getMessage());
        }
        
        return overview;
    }

}